<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/8/2
 * Time: 16:42
 */
namespace backend\models;

use Yii;
use yii\db\ActiveRecord;
use common\helps\tools;

class GoodsListEdit extends ActiveRecord{
    const STATUS_ENABLE = 1;
    const STATUS_DISABLE = 0;
    
    const USE_FLG_YES			=1;
    const USE_FLG_NO			=0;

    public static function tableName(){
        return '{{%goods_list_edit}}';
    }

    public function rules(){
        return [
            ['use_flg','default','value'=>self::STATUS_DISABLE],
            ['creator','getCreator'],
            ['create_time','date']
        ];
    }

    /**
     * @获取创建人
     */
    public function getCreator(){
        $userInfo = \common\helps\tools::getloginUserInfo();
        if($userInfo){
            $userName = $userInfo->userName;
        }else{
            $userName = '';
        }
        return $userName;
    }
    
    /**
     * @获取创建人
     */
    public function getLogWriter(){
        $userInfo = \common\helps\tools::getloginUserInfo();
        if($userInfo->userId){
            $user = UserMaster::find()->select('user_name,true_name')->where('id='.$userInfo->userId)->asArray()->one();
            $userName = $user['user_name'].' '.$user['true_name'];
        }else{
            $userName = '';
        }
        return $userName;
    }

    //新增主商品
    public function addNewMainGoods($data){
        unset($data['id']);
        $data['creator'] = $this->getCreator();
        $data['create_time'] = date('Y-m-d H:i:s',time());
        $ret = Yii::$app->db->createCommand()->insert('j_goods_list_edit',$data)->execute();
        return $ret;
    }

    //编辑主商品
    public function UpdateMainGoods($data){
        unset($data['id']);
        unset($data['creator']);
        unset($data['create_time']);
        unset($data['is_publish']);
        unset($data['is_examine']);
        $data['use_flg'] = 1;
        $data['editor'] = $this->getCreator();
        $data['edit_time'] = date('Y-m-d H:i:s',time());
        $ret = $this::updateAll($data, "main_goods_id=:main_goods_id",array(':main_goods_id'=>$data['main_goods_id']));
        return $ret;
    }

    //商品上下架时，主商品列表的上下架
    public function changeUseFlg($goods_list,$use_flg,$main_goods_id){
        $main_where = ['main_goods_id'=>$main_goods_id];
        $main_goods = $this::find()->where($main_where)->asArray()->one();
        if(!empty($main_goods)){//主商品表中有该条数据
            if($use_flg == 1){
                $data['use_flg'] = $use_flg;
                $data['editor'] = $this->getCreator();
                $data['edit_time'] = date('Y-m-d H:i:s',time());
                $ret = $this::updateAll($data,$main_where);
                if(!$ret){
                    return false;
                }
            }else{
                foreach($goods_list as $value){
                    if($use_flg == $value['use_flg']){
                        $type = 1;
                    }else{
                        $type = 0;
                        break;
                    }
                }
                if(!empty($type)){
                    $data['use_flg'] = $use_flg;
                    $data['editor'] = $this->getCreator();
                    $data['edit_time'] = date('Y-m-d H:i:s',time());
                    $ret = $this::updateAll($data,$main_where);
                    if(!$ret){
                        return false;
                    }
                }
            }
        }
        return true;
    }

    //同步主商品
    public function publishMainList($main_goods_id_list){
        $is_complete = true;
        foreach($main_goods_id_list as $goods){
            $need_goods = $goods;
            if($goods['is_publish'] == 1){ //已同步
                unset($need_goods['is_publish']);
                unset($need_goods['id']);
                unset($need_goods['creator']);
                unset($need_goods['create_time']);
                $need_goods['editor'] = $this->getCreator();
                $need_goods['edit_time'] = date('Y-m-d H:i:s',time());
                $res = GoodsList::updateAll($need_goods,'main_goods_id=:main_goods_id',array(':main_goods_id'=>$goods['main_goods_id']));
            }else{ //未同步
                unset($need_goods['is_publish']);
                unset($need_goods['id']);
                $need_goods['creator'] = $this->getCreator();
                $need_goods['create_time'] = date('Y-m-d H:i:s',time());
                if (!$need_goods['goods_id'] || !$need_goods['sku']){
                    continue;
                }
                $res = Yii::$app->db->createCommand()->insert('j_goods_list',$need_goods)->execute();
            }
            if(!$res){
                $is_complete = false;
                break;
            }
        }
        return $is_complete;
    }
    
    //根据$goods_id获取主商品列表以及相应品牌信息 TODO 待修改
    public function getMainGoodsListByGoodsId($main_goods_id){
        /*$main_goods_list = array();*/
        if(!empty($main_goods_id)){
            $where = ['l.use_flg'=>self::USE_FLG_YES,'l.main_goods_id'=>$main_goods_id];
            $main_goods_list = $this::find()->alias('l')->where($where)->
            leftJoin('j_goods_brand as s','l.brand_id = s.id')->select('l.*,s.country_icon,s.country_name,s.brand_story,s.logo')->asArray()->one();
        }
        
        if(empty($main_goods_list)){
            $main_goods_list = array();
        }
        /*else{
         $command = (new \yii\db\Query())->select(['min(sale_price) as min_price', 'max(sale_price) as max_price'])
         ->from('j_goods_sale')->where(['main_goods_id' => $main_goods_id])->createCommand();
         $post = $command->queryOne();
         $main_goods_list['min_price'] = $post['min_price'];
         $main_goods_list['max_price'] = $post['max_price'];
         }*/
        return $main_goods_list;
    }
    
    public function getGoodsListId($goods_id){
        $where = ['goods_id'=>$goods_id];
        $result = $this::find()->where($where)->asArray()->one();
        return $result['id'];
    }
    
    //根据main_goods_id获取主商品列表
    public function getMainGoodsList($main_goods_id){
        if(!empty($main_goods_id)){
            $where = ['use_flg'=>1,'main_goods_id'=>$main_goods_id];
            $main_goods_list = $this::find()->where($where)->asArray()->all();
        }
        if(empty($main_goods_list)){
            $main_goods_list = array();
        }
        return $main_goods_list;
    }
    
    //后台商品信息修改写入日志
    public function writeGoodsLog($mian_goods_id,$goods_id='',$type,$new_data='',$old_data='',$is_examine=''){
        $goods_log = new GoodsLog();
        $goods_log->main_goods_id = $mian_goods_id;
        $goods_log->goods_id = $goods_id ? $goods_id : 0;
        $goods_log->type = $type;
        $change_field = [];
        switch ($type){
            /**
             * 1：创建商品基础资料
             * 2：修改商品基础资料
             * 4：创建子商品
             * 5：修改子商品
             * 7：审核基础资料
             * 8：审核子商品
             */
            case 1:
            case 2:
            case 4:
            case 5:
            case 7:
            case 8:
                if (in_array($type, [1,4,7,8])){
                    unset($new_data['main_goods_id'],$new_data['goods_id']);
                    $goods_log->examine_flg = $is_examine;
                }
                if (is_array($new_data) && count($new_data) > 0)foreach ($new_data as $key=>$val){
                    if (tools::arrayHasValue($old_data,$key) && $new_data[$key] == $old_data[$key]){
                        unset($old_data[$key]);
                    }else{
                        if ($key == MARKING_IMG_ID){
                            $marking_img_id = [$new_data[$key]];
                            if (tools::arrayHasValue($old_data,$key)){
                                $marking_img_id[] = $old_data[$key];
                            }
                            $goods_marking = GoodsMarkingImg::find()->select('id,img_name')->where([
                                'id'=>array_unique(array_filter($marking_img_id))
                            ])->asArray()->all();
                            $goods_marking = count($goods_marking) > 0 ? array_combine(array_column($goods_marking, 'id'), $goods_marking) : [];
                            $old_data[$key] = tools::arrayHasValue($old_data,$key) && tools::arrayHasValue($goods_marking,$old_data[$key]) ? $goods_marking[$old_data[$key]]['img_name'] : '空值';
                            $new_data[$key] = tools::arrayHasValue($new_data,$key) && tools::arrayHasValue($goods_marking,$new_data[$key]) ? $goods_marking[$new_data[$key]]['img_name'] : '空值';
                        }elseif (in_array($key, [CATEGORY_STEP1,CATEGORY_STEP2])){
                            $category_id = [$new_data[$key]];
                            if (tools::arrayHasValue($old_data,$key)){
                                $category_id[] = $old_data[$key];
                            }
                            $goods_category = GoodsCategory::find()->select('id,category_name')->where([
                                'id'=>array_unique(array_filter($category_id))
                            ])->asArray()->all();
                            $goods_category = count($goods_category) > 0 ? array_combine(array_column($goods_category, 'id'), $goods_category) : [];
                            $old_data[$key] = tools::arrayHasValue($old_data,$key) && tools::arrayHasValue($goods_category,$old_data[$key]) ? $goods_category[$old_data[$key]]['category_name'] : '空值';
                            $new_data[$key] = tools::arrayHasValue($new_data,$key) && tools::arrayHasValue($goods_category,$new_data[$key]) ? $goods_category[$new_data[$key]]['category_name'] : '空值';
                        }elseif ($key == TAG_ID){
                            $tag_id = [$new_data[$key]];
                            if (tools::arrayHasValue($old_data,$key)){
                                $tag_id[] = $old_data[$key];
                            }
                            $goods_tag = GoodsTag::find()->select('id,tag_name')->where([
                                'id'=>array_unique(array_filter($tag_id))
                            ])->asArray()->all();
                            $goods_tag = count($goods_tag) > 0 ? array_combine(array_column($goods_tag, 'id'), $goods_tag) : [];
                            $old_data[$key] = tools::arrayHasValue($old_data,$key) && tools::arrayHasValue($goods_tag,$old_data[$key]) ? $goods_tag[$old_data[$key]]['tag_name'] : '空值';
                            $new_data[$key] = tools::arrayHasValue($new_data,$key) && tools::arrayHasValue($goods_tag,$new_data[$key]) ? $goods_tag[$new_data[$key]]['tag_name'] : '空值';
                        }elseif ($key == BRAND_ID){
                            $brand_id = [$new_data[$key]];
                            if (tools::arrayHasValue($old_data,$key)){
                                $brand_id[] = $old_data[$key];
                            }
                            $goods_brand = GoodsBrand::find()->select('id,brand_name')->where([
                                'id'=>array_unique(array_filter($brand_id))
                            ])->asArray()->all();
                            $goods_brand = count($goods_brand) > 0 ? array_combine(array_column($goods_brand, 'id'), $goods_brand) : '空值';
                            $old_data[$key] = tools::arrayHasValue($old_data,$key) && tools::arrayHasValue($goods_brand,$old_data[$key]) ? $goods_brand[$old_data[$key]]['brand_name'] : '空值';
                            $new_data[$key] = tools::arrayHasValue($new_data,$key) && tools::arrayHasValue($goods_brand,$new_data[$key]) ? $goods_brand[$new_data[$key]]['brand_name'] : '空值';
                        }elseif ($key == HIDDEN_PRICE){
                            $old_data[$key] = tools::arrayHasValue($old_data,$key) ? $GLOBALS['GOODS_HIDDEN_PRICE'][$old_data[$key]] : '空值';
                            $new_data[$key] = tools::arrayHasValue($new_data,$key) ? $GLOBALS['GOODS_HIDDEN_PRICE'][$new_data[$key]] : '空值';
                        }elseif ($key == USE_FLG){
                            $old_data[$key] = tools::arrayHasValue($old_data,$key) ? $GLOBALS['GOODS_USE_FLG'][$old_data[$key]] : '空值';
                            $new_data[$key] = $GLOBALS['GOODS_USE_FLG'][$new_data[$key]];
                        }elseif ($key == FORSALE){
                            $old_data[$key] = tools::arrayHasValue($old_data,$key) ? $GLOBALS['GOODS_FORSALE'][$old_data[$key]] : '空值';
                            $new_data[$key] = $GLOBALS['GOODS_FORSALE'][$new_data[$key]];
                        }elseif ($key == IS_MAIN){
                            $old_data[$key] = tools::arrayHasValue($old_data,$key) ? ($old_data[$key] == 1 ? '是' : '否') : '空值';
                            $new_data[$key] = $new_data[$key] == 1 ? '是' : '否';
                        }elseif($key == SOURCE_URL){
                            if ($type == 5){
                                $source_edit = GoodsSourceEdit::find()->where('goods_id='.$goods_id)->asArray()->all();
                                $old_data[$key] = count($source_edit) > 0 ? array_column($source_edit, 'source_url') : [];
                            }
                            $new_data[$key] = $new_data[$key] ? $new_data[$key] : [];
                        }elseif ($key == NAVIGATION_IDENTIFICATION){
                            $navigation_identification_id = tools::arrayHasValue($old_data,$key) ? array_merge($new_data[$key],$old_data[$key]) : $new_data[$key];
                            $navigation_identification = NavigationIdentification::find()->select('id,name')->where([
                                'id'=>array_unique(array_filter($navigation_identification_id))
                            ])->asArray()->all();
                            $navigation_identification = array_combine(array_column($navigation_identification, 'id'), $navigation_identification);
                            $new = $old = [];
                            if (tools::arrayHasValue($new_data,$key) && count($new_data[$key]) > 0)foreach ($new_data[$key] as $new_name){
                                $new[] = $navigation_identification[$new_name]['name'];
                            }
                            if (tools::arrayHasValue($old_data,$key) && count($old_data[$key]) > 0)foreach ($old_data[$key] as $old_name){
                                $old[] = $navigation_identification[$old_name]['name'];
                            }
                            $old_data[$key] = count($old) > 0 ? implode('/', $old) : '空值';
                            $new_data[$key] = count($new) > 0 ? implode('/', $new) : '空值';
                        }else{
                            $old_data[$key] = tools::arrayHasValue($old_data,$key) ? $old_data[$key] : '空值';
                            $new_data[$key] = $new_data[$key] ? $new_data[$key] : '空值';
                        }
                        $change_field[$GLOBALS['GOODS_FIELD'][$key]] = tools::arrayHasValue($old_data,$key) ? $old_data[$key] : '空值';
                        $new_data[$GLOBALS['GOODS_FIELD'][$key]] = $new_data[$key];
                    }
                    unset($new_data[$key]);
                }
                $goods_log->new_data = count($new_data) > 0 ? json_encode($new_data,JSON_UNESCAPED_UNICODE) : '';
                $goods_log->old_data = count($change_field) > 0 ? json_encode($change_field,JSON_UNESCAPED_UNICODE) : '';
                if (count($new_data) == 0 && count($change_field) == 0){
                    return true;
                }
                break;
            //修改规格
            case 3:
                $new_spce = ['规格'=>(count($new_data) > 0 ? implode('、', array_column($new_data, 'spec_name')) : '空值')];
                $old_spce = ['规格'=>(count($old_data) > 0 ? implode('、', array_column($old_data, 'spec_name')) : '空值')];
                if ($new_spce == $old_spce){
                    return true;
                }
                $goods_log->new_data = count($new_spce) > 0 ? json_encode($new_spce,JSON_UNESCAPED_UNICODE) : '';
                $goods_log->old_data = count($old_spce) > 0 ? json_encode($old_spce,JSON_UNESCAPED_UNICODE) : '';
                break;
            //修改子商品上下架
            case 6:
                $key = $GLOBALS['GOODS_FIELD']['use_flg'];
                $goods_log->new_data = json_encode([$key=>$GLOBALS['GOODS_USE_FLG'][$new_data['use_flg']]],JSON_UNESCAPED_UNICODE);
                $goods_log->old_data = json_encode([$key=>$GLOBALS['GOODS_USE_FLG'][$old_data['use_flg']]],JSON_UNESCAPED_UNICODE);
                break;
            //创建商品搭配
            case 9:
                $key = $GLOBALS['GOODS_FIELD']['goods_collocation'];
                $new = $old = [];
                if (is_array($new_data) && count($new_data) > 0) foreach ($new_data as $new_data_val){
                    $new[] = $new_data_val['sku'].'(商品号：'.$new_data_val['goods_id'].')';
                }
                if (is_array($old_data) && count($old_data) > 0) foreach ($old_data as $old_data_val){
                    $old[] = $old_data_val['sku'].'(商品号：'.$old_data_val['goods_id'].')';
                }
                $goods_log->new_data = json_encode([$key=>count($new) > 0 ? implode('、', $new) : ''],JSON_UNESCAPED_UNICODE);
                $goods_log->old_data = json_encode([$key=>count($old) > 0 ? implode('、', $old) : ''],JSON_UNESCAPED_UNICODE);
                break;
            //11：同步商品
            case 11: break;
        }
        $goods_log->operator = $this::getLogWriter();
        $goods_log->oper_time = date('Y-m-d H:i:s');
        $goods_log->save();
        $id = $goods_log->attributes['id'];
        if (!$id){
            return false;
        }
        return true;
    }
}